class LoginController < ApplicationController
  before_filter :authorize, :except => [:login, :register, :index]
  
  def index    
  end

  def logout    
    username = User.find(session[:user_id]).username
    session[:user_id] = nil
    info("User #{username} successfully logged out", :notice)
    redirect_to(:action => "index")    
  end
  
  def login    
    redirect_to(:action => :index) and return unless(session[:user_id].nil?)           
    
    if(request.get?)
      @user = User.new
    else
      logged_in_user = User.authenticate(params[:user][:username],params[:user][:password])
      if logged_in_user
        session[:user_id] = logged_in_user.user_id        
        redirect_to(:controller => '/user/catalog', :action => :list, :id => logged_in_user.root_catalog.id)
      else
        info("Wrong username or password.", :error)
        redirect_to(:action => "login")
      end
    end
    
  end

  def register
    if (request.get?)
      @user = User.new
    else
      @user = User.new(params[:user])      
      if @user.save
        info("User #{@user.username} registered succesfully", :notice)
        redirect_to(:action => 'login')      
      end
    end
  end
 
  def edit    
    if (request.get?)            
      @user = User.find(session[:user_id])     
      redirect_to( :action => :index) and return unless(@user)
      
    else
      @user = User.find(session[:user_id])
      @user.first_name = params[:user][:first_name]
      @user.last_name = params[:user][:last_name]
      @user.email = params[:user][:email]
      @user.password = params[:user][:password]
      @user.password_confirmation = params[:user][:password_confirmation]
      
      if(@user.save)
        info("User info successfully saved", :notice)
        redirect_to(:action => :index)
      else
      end
      
    end    
  end
  
end
